package com.bfsd.tieba.agent.tieba_agent.controller;

import org.springframework.core.io.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;

/**
 * @author 胡亮
 * @since 20点44分
 */
@RestController
@Slf4j
public class LLMController {

    private final ChatClient chatClient;

    @Value("classpath:prompts/base.st")
    private Resource systemPrompt;

    public LLMController(ChatClient chatClient) {
        this.chatClient = chatClient;
    }

    @GetMapping("/toolChat")
    public String toolChat(@RequestParam("message") String message) {
        System.out.println("用户输入：" + message);
        //为什么用这种方式注入提示词，这种方式支持变量替换，在createMessage的参数里用map就可以替换提示词里的{}包裹的参数
        SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemPrompt);
        Message systemMessage = systemPromptTemplate.createMessage();
        String result =
                chatClient.
                        prompt(new Prompt(systemMessage))
                        .user(message)
                        .call()
                        .content();
        System.out.println("智能体回复：");
        splitStringByRegex(result, 40);
        return result;
    }

    public static void splitStringByRegex(String text, int lineLength) {
        //这个方法只是为了打印自动换行方便看
        String regex = "(?<=\\G.{" + lineLength + "})"; // 每N个字符分割
        Arrays.stream(text.split(regex))
                .forEach(System.out::println);
    }

}
